<!-- 产线状态登记 -->
<template>
  <basic-container class="production-page">
    <avue-crud
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" v-if="permission.productLineStatysRegister_register" @click="$refs.crud.rowAdd()">登 记</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
    <!-- 物料基础数据 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { queryLineRecord, changeLineRecord, LineRecordPage } from '@/api/product/productionline';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: '',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'PRODUCTION_LINE_STATYS_REGISTER',
      changeData: {},
      defaults: {},
      form: {},
      query: {},
      loading: false,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        viewTitle: '详情',
        viewBtnText: '详情',
        addBtn: false,
        addTitle: '登记',
        editBtn: false,
        delBtn: false,
        selection: false,
        dialogClickModal: false,
        menu: true,
        menuWidth: 100,
        labelWidth: 130,
        columnBtn: false,
        column: [
          {
            label: '车间',
            prop: 'workshopName',
            searchSpan: 5,
            span: 24,
            order: 1
          },

          {
            label: '产线',
            prop: 'lineName',
            search: true,
            searchType: 'input',
            type: 'search',
            searchSpan: 5,
            span: 24,
            disabled: true,
            order: 2,
            appendClick: () => {
              this.assignment();
            },
            rules: [
              {
                required: true,
                message: '请输入产线',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '当前状态',
            prop: 'state',
            type: 'select',
            search: true,
            disabled: true,
            searchSpan: 4,
            span: 24,
            order: 3,
            html: true,
            formatter: (val) => {
              switch (val.state) {
                case '1':
                  return `<span class="stateWords-danger">停线</span>`;
                case '2':
                  return `<span class="stateWords-success">生产</span>`;
                default:
                  break;
              }
            },
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=line_status',
            rules: [
              {
                required: true,
                message: '请选择当前状态',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '状态变更',
            prop: 'stateChange',
            hide: true,
            type: 'select',
            span: 24,
            order: 4,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=line_status',
            rules: [
              {
                required: true,
                message: '请选择状态变更',
                trigger: 'blur'
              }
            ],
            change: ({ value, column }) => {
              this.changeLineChangeStatusId(value);
            }
          },
          {
            label: '变更人',
            span: 24,
            prop: 'changedBy'
          },
          {
            label: '变更时间',
            prop: 'changeTime',
            type: 'date',
            searchSpan: 8,
            searchType: 'datetimerange',
            search: true,
            disabled: true,
            span: 24,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
          },
          {
            label: '变更原因',
            prop: 'reason',
            type: 'select',
            span: 24,
            order: 5,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入变更原因',
                trigger: 'blur'
              }
            ],
            formatter: (row, value, label, column) => {
              if (value == '0') {
                return (label = '');
              } else {
                return label;
              }
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=line_reason'
          },
          {
            label: '变更前状态时长',
            span: 24,
            prop: 'lastDurationFormat'
          },
          {
            label: '状态',
            prop: 'status',
            span: 24,
            type: 'select',
            dicData: [
              {
                label: '正常',
                value: 1
              },
              {
                label: '异常',
                value: 0
              }
            ],
            hide: true
          },
          {
            label: '备注',
            prop: 'remark',
            hide: true,
            span: 24,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            maxlength: 300,
            showWordLimit: true
          }
        ]
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.productLineStatysRegister_view, false)
      };
    }
  },
  methods: {
    rowSave(row, done, loading) {
      if (row.state == row.stateChange) {
        this.$message.warning('状态变更和当前状态一致，请重新选择');
        loading();
        return;
      }
      if (row.stateChange == '1' && row.reason == '') {
        this.$message.warning('状态变更为停线时，请选择变更原因');
        loading();
        return;
      }
      let param = {
        changeBy: this.changeData.changeBy,
        changeTime: this.changeData.changeTime,
        id: this.changeData.id,
        lineCode: this.changeData.lineCode,
        lineId: this.changeData.lineId,
        reason: Number(row.reason),
        state: Number(row.stateChange),
        fromState: row.state + '',
        remark: row.remark
      };
      if (param.state !== 1) {
        delete param.reason;
      }
      changeLineRecord(param)
        .then((res) => {
          this.$message.success('产线状态变更完成');
          this.onLoad(this.page, this.query);
          done();
        })
        .catch((err) => {
          loading();
        });
    },
    beforeOpen(done, type) {
      this.defaults.remark.display = true;
      if (['view'].includes(type)) {
        // 查看
        this.defaults.lineName.type = 'input';
        this.defaults.status.display = true;
        this.defaults.changedBy.display = true;
        this.defaults.lastDurationFormat.display = true;
        this.defaults.stateChange.display = false;
        this.defaults.workshopName.display = true;
      } else {
        // 登记
        this.defaults.lineName.type = 'search';
        this.defaults.status.display = false;
        this.defaults.changedBy.display = false;
        this.defaults.lastDurationFormat.display = false;
        this.defaults.stateChange.display = true;
        this.defaults.workshopName.display = false;
      }
      done();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.changeTime && params.changeTime.length > 0) {
        params.startTime = params.changeTime[0];
        params.endTime = params.changeTime[1];
        delete params.changeTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    onLoad(page, params = {}) {
      this.loading = true;
      LineRecordPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map((rec) => {
          rec.fromState = rec.fromState === null ? '1' : rec.fromState + '';
          rec.state = rec.state + '';
          rec.reason = rec.reason === null ? '' : rec.reason + '';
          return rec;
        });
        setTimeout(() => {
          this.loading = false;
        }, 500);
      });
    },
    // 产线名称 弹框 配置
    assignment() {
      this.modalName = 'productionModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产线（双击进行选择）',
        url: '/api/mes-product/productionline/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '产线名称',
            prop: 'name',
            search: true,
            order: 3,
            rules: [
              {
                required: true,
                message: '请输入产线名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产线编码',
            prop: 'code',
            order: 2,
            rules: [
              {
                required: true,
                message: '请输入产线编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '车间名称',
            prop: 'workshopId',
            type: 'select',
            search: true,
            hide: true,
            order: 4,
            props: {
              label: 'workshopName',
              value: 'workshopId'
            },
            rules: [
              {
                required: true,
                message: '请选择车间名称',
                trigger: 'change'
              }
            ],
            dicFlag: true,
            dicUrl: '/api/mes-admin/workshop/key-value'
          },
          {
            label: '车间名称',
            prop: 'workshopName'
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            order: 6,
            maxRows: 3,
            minRows: 3,
            maxlength: 300,
            showWordLimit: true
          }
        ]
      };
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'productionModal':
          this.changeData.lineId = this._get(rowData, 'id', '');
          this.changeData.lineCode = this._get(rowData, 'code', '');
          this.changeData.lineName = this._get(rowData, 'name', '');
          this.form.lineCode = this._get(rowData, 'code', '');
          this.form.lineId = this._get(rowData, 'id', '');
          this.form.lineName = this._get(rowData, 'name', '');
          // 根据产线Id查询产线变更记录
          this.getProductLineChangeRecord(this.changeData.lineId);
          break;
        default:
          break;
      }
    },
    getProductLineChangeRecord(lineId) {
      queryLineRecord(lineId)
        .then((res) => {
          if (res && res.status == 200) {
            let data = res.data.data;
            this.changeData.id = data.id;
            this.changeData.changeBy = data.changeBy;
            this.changeData.fromState = data.fromState === null ? '1' : data.fromState + '';
            this.changeData.state = data.state + '';
            this.changeData.changeTime = data.changeTime;
            this.changeData.remark = '';
            this.changeData.reason = data.reason === null ? '' : data.reason + '';

            this.form.fromState = data.fromState === null ? '1' : data.fromState + '';
            this.form.state = data.state + '';
            this.form.changeTime = data.changeTime;
            this.form.reason = data.reason === null ? '' : data.reason + '';
          }
        })
        .catch((err) => {});
    },
    changeLineChangeStatusId(value) {
      if (value == '1') {
        this.defaults.reason.rules[0].required = true;
        this.defaults.reason.display = true;
      } else {
        this.defaults.reason.rules[0].required = false;
        this.defaults.reason.display = false;
      }
      this.form.reason = '';
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss"></style>
